package com.qf.qfuser.controller;

import com.qf.qfcommons.pojo.Order;
import com.qf.qfcommons.pojo.R;
import com.qf.qfcommons.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.print.attribute.standard.PrinterURI;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

//@RestController
//@RequestMapping("/user")
public class UserController {

//    @Autowired
//    UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    //从spring容器中获取一个服务发现的对象
    @Autowired
    private DiscoveryClient discoveryClient;

    //因为eureka-client依赖中，已经引入了ribbon依赖，所以从spring容器中获取一个负载均衡器对象
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    private AtomicInteger ai = new AtomicInteger(0);

    @GetMapping("/{id}")
    public R findOrders(@PathVariable("id") Integer id) throws InterruptedException {
//        List<Order> orders = userService.findById(id);
//        return R.success().putData(orders);

       /* List<ServiceInstance> instances = discoveryClient.getInstances("QF-ORDER");

        //随机负载均衡
//        int idx = new Random().nextInt(instances.size());
//        ServiceInstance instance = instances.get(idx);

        //模拟轮询负载均衡 0-1-0-1-0-1...
        int i = ai.incrementAndGet();
        int idx = i % instances.size();
        ServiceInstance instance = instances.get(idx);*/

        ServiceInstance instance = loadBalancerClient.choose("QF-ORDER");

        //获取实例的ip
        String host = instance.getHost();
        //获取实例的端口
        int port = instance.getPort();


        //通过RestTemplate向Order服务发起请求，获取订单数据
        R r = restTemplate.getForObject("http://"+host+":"+port+"/order/"+id, R.class);
        return r;
    }
}
